package com.leyou.item.service;

import com.leyou.common.exception.LyException;
import com.leyou.item.entity.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
@Slf4j
public class ItemService {
    @Transactional
    public Item saveItem(Item item) {
        // 判断价格是否为空
        if (item.getPrice() == null) {
            throw new LyException(400, "价格不能为空！");
        }
        if (item.getName() == null) {
            throw new LyException(400, "名称不能为空！");
        }

        // 随机生成id，模拟数据库的新增
        int id = new Random().nextInt(100);

        if (id < 50) {
            throw new LyException(500, "商品已经存在， id=" + id);
        }
        item.setId(id);
        // 返回新增之后的对象，回显id
        return item;
    }
}
